package com.tz.core;

import com.tz.auth.AuthHelper;
import com.tz.auth.AuthPassport;
import com.tz.bean.Permission;
import com.tz.util.TmStringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.tz.util.TzConstant.SESSION_ALL_PERMISSION;

/**
 * Created by Administrator on 2017-3-9.
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if(handler.getClass().isAssignableFrom(HandlerMethod.class)){
            AuthPassport authPassport = ((HandlerMethod) handler).getMethodAnnotation(AuthPassport.class);

            //没有声明需要权限,或者声明不验证权限
            if(authPassport == null || authPassport.validate() == false)
                return true;
            else{
                String uri = request.getRequestURI();
                String path = request.getContextPath();
                String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";
                if (!uri.contains("admin/index") && !uri.contains("admin/logout") && !uri.contains("admin/refuse")  && !uri.contains("template") ) {
                    List<Permission> allPermissions = (List<Permission>) request.getSession().getAttribute(SESSION_ALL_PERMISSION);
                    if(allPermissions.size()>0){
                        boolean hasPermission=false;
                        String requestServletPath=request.getServletPath();
                        for(Permission permissionMenu : allPermissions){
                            Pattern pattern = Pattern.compile(permissionMenu.getUrl(),Pattern.CASE_INSENSITIVE);
                            Matcher matcher = pattern.matcher(requestServletPath);
                            if(matcher.find()){
                                hasPermission=true;
                                AuthHelper.setRequestPermissionMenu(request, permissionMenu);
                            }
                            if(hasPermission){
                                break;
                            }
                        }
                        if(hasPermission)
                            return true;
                        else {
                            //执行是一个ajax请求还是一个普通请求
                            String requestType  =  request.getHeader("X-Requested-With");
                            //如果是ajax请求
                            if(TmStringUtils.isNotEmpty(requestType) && requestType.equalsIgnoreCase("XmlHttpRequest")) {
                                response.setHeader("SESSIONSTATUS", "TIMEOUT");
                                response.setHeader("CONTEXTPATH", basePath+"admin/refuse");
                                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                                return false;
                            }else{
                                response.sendRedirect(basePath+ "admin/refuse");
                            }
                        }
                    }else{
                        StringBuilder urlBuilder=new StringBuilder(request.getContextPath());
                        urlBuilder.append("/login");
                        if(request.getServletPath()!=null && !request.getServletPath().isEmpty()){
                            urlBuilder.append("?returnUrl=");
                            StringBuilder pathAndQuery=new StringBuilder(request.getServletPath());
                            if(request.getQueryString()!=null && !request.getQueryString().isEmpty()){
                                pathAndQuery.append("?");
                                pathAndQuery.append(request.getQueryString());
                            }
                            urlBuilder.append(URLEncoder.encode(pathAndQuery.toString(), "UTF-8"));
                        }
                        response.sendRedirect(urlBuilder.toString());
                    }
                    return false;
                }else{
                    return true;
                }

            }
        }
        else
            return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        System.out.println("请求结束执行的方法..........");

    }
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        System.out.println("响应已经被渲染成功后执行的方法..........");

    }
}
